<template>
    <main-wrap style="background: #fcf7ee;">
        <div class="release-from">
            <!-- <div class="fromItem">
                <div class="name">发布位置</div>
                <div>
                    <position-select v-model="publishingLocation"/>
                </div>
            </div> -->
            <div class="fromItem">
                <div class="name">标题</div>
                <input type="text" placeholder="请输入标题" v-model="fmData.title"/>
            </div>
            <div class="fromItem">
                <div class="name">分类</div>
                <div>
                    <category-select v-model="classfly"/>
                </div>
            </div>
            <div class="fromItem">
                <div class="name">话题详情</div>
                <textarea placeholder="输入话题详情~" v-model="fmData.questionContent"></textarea>
            </div>

            <div class="fromItem" style="display: none;">
                <div class="name">上传附件</div>
                <div class="annexBox">
                    <upload-file v-model="fileLists"/>
                </div>
            </div>
        </div>
        <template v-slot:footer>
            <div class="releaseBtn">
                <Button text="立即发表" @click="save"></Button>
            </div>
        </template>
    </main-wrap>
</template>

<script>
import { mapGetters } from "vuex";
import { Toast,Icon as vanIcon} from 'vant';
import mainWrap from 'cps/public/mainWrap'
import Button from 'cps/public/Button'
import categorySelect from './components/categorySelect'
//import positionSelect from './components/positionSelect'
import uploadFile from './components/uploadFile'
import {getQuestionDetail,editQuestion,addQuestion,getCustomList,getUserInfo,sendTemplateMsg,getCompanyList} from '@/api/index.js'
export default {
    components:{
        mainWrap,
        Button,
        categorySelect,
        //positionSelect,
        uploadFile
    },
    data(){
        return{
            fmData:{privacy:1},
            classfly:'',
            querys:{}, // url参数集合
            publishingLocation:'',
            fileLists:[],
        }
    },
    computed: {
        ...mapGetters({
             //userInfo:'user/userInfo',
        }),
    },
    async created(){
        this.querys = this.$route.query  // 参数集合:本文组件中用到的参数：问题qid、小程序openid、成员公司curCompanyId、成员公司母公司motherCompanyId、成员公司服务主curServiceId
        console.log("this.querys:",this.querys)
        if(this.querys.qid){
            // 获取问题详情
            const res = await getQuestionDetail(this.querys.qid,this.querys.uid)
            if(res.code == 200){
                this.fmData.questionContent = res.data.questionContent
                this.fmData.title = res.data.title
                this.fileLists = res.data.annex || []
                this.classfly = (res.data.classifyIds && res.data.classifyIds.length>0)?res.data.classifyIds[0]._id:''
            }
        }
    },
    mounted(){
        this.$nextTick(()=>{
            var script = document.createElement('script');
            script.type = 'text/javascript';
            script.src = '/js/uni.webview.1.5.2.js';
            document.body.appendChild(script);
        })
        
    },
    methods:{  
        async save(){   
            if(!this.fmData.title){
                return Toast('请输入标题')
            }else if(!this.fmData.questionContent){
                return Toast('请输入话题详情')
            }
            
            if(this.classfly){
                this.fmData.classifyIds = [this.classfly]
            }
            
            if(this.querys.qid){
                this.editSumbit()
            }else{
                this.addSumbit()
            }
        },
        async editSumbit(){
            //this.fmData.annex = this.fileLists
            const res = await editQuestion({
                id:this.querys.qid,
                title:this.fmData.title,  // 微信验证添加的字段
                content:this.fmData.questionContent,  // 微信验证添加的字段
                openid:this.querys.openid,  // 微信验证添加的字段
                scene:3, // 微信验证添加的字段
                params:this.fmData
            })
            if(res.code == 200){
                Toast('修改成功')
                uni.navigateBack({delta:1}) // 返回
            }else{
                Toast('修改失败，请重试！')
            }
        },
        async addSumbit(){
           
            // 附件
            // if(this.fileLists.length>0){
            //     this.fmData.annex = this.fileLists
            // }

            const res = await addQuestion({
                userId:this.querys.uid,
                from:'EJConsult',
                content:this.fmData.questionContent,  // 微信验证添加的字段
                openid:this.querys.openid,  // 微信验证添加的字段
                scene:3,// 微信验证添加的字段
                groupId:this.querys.groupId,
                ...this.fmData
            })
            if(res.code == 200){
                Toast('发布成功！')
                // if(this.querys.appUserType==2){ // 企业成员咨询时，发送模板消息
                //     get_taecher_openid2(res.data._id) // 获取教师的ej在线公众号openid，发送模板消息
                // }
                //uni.$emit('refreshIndex')  // 刷新主页数据
                uni.navigateBack({delta:1}) // 返回
            }else if(res.code == 8000){
                Toast('发布的内容不合法，请重新输入！')
            }else{
                Toast('发布失败，请重试！')
            }
        },
        // 获取服务于当前公司的教师（后台添加公司时指派的教师）
        async get_taecher_openid2(qustionId){
            // 获取当前公司的服务专家
            const rt2 = await getCustomList({
                customId:this.querys.curCompanyId,
                serviceId:this.querys.curServiceId,
                serviceType:2,// 服务主类型，1为个人，2为公司
                customType:2,  // 客户类型：1为个人客户，2为企业客户
            })
            if(rt2 && rt2.data.data && rt2.data.data.length>0){
                // 如果有多调，则只获取第一条
                const item = rt2.data.data[0]
                const tLists = item.experter
                for(let i=0;i<tLists.length;i++){
                    const openid = tLists[i].openid
                    console.log("公众号openid:",openid)
                    if(openid){
                        send_template_msg(openid,qustionId)	
                    }
                }
            }
        },
        async send_template_msg(openid,qustionId){
				//console.log("openid:",openid)
				//return
				// 提问人当前所在公司
				let cCompany = {}
				const res = await getCompanyList({_id:this.querys.curCompanyId}) 
                if(res.data.data && res.data.data.length>0){
                    cCompany = res.data.data[0]
                } 
                // 用户信息
                let userInfo ={}
                const res2 = await getUserInfo(this.querys.uid)
                if(res2.code == 200){
                    userInfo = res.data
                }
				const mbTitle = `${userInfo.name || userInfo.nickname}(${cCompany.name})`
				const qaTitle = this.fmData.title || this.fmData.questionContent
				sendTemplateMsg({
					openId:openid, // EJ在线公众号openId
					from:'EJOnline',  // EJ在线公众号
					//url:'http://mobile.ej12366.video/course/62d60fa54e67342a62b49e5b',
					tid:'yZbn1gKUMUeLzN4lra8xI3tlzYz4K1FFaQjM486oQ8Q', // 模板id
					miniprogram:{
					 "appid":"wxb1a6803f74149adb",  // 小程序appid
					 "pagepath":"pages/qa/detail?id="+qustionId
				    },
					dataObj:{
							"thing17": { // 提问人姓名+所在公司名称
								"value":mbTitle.substring(0,20),
								"color":"#717171"
							},
							"thing3":{ // 问题标题
								"value":qaTitle.substring(0,20),
								"color":"#000000"
							},
							"phone_number8": { // 提问人电话
								"value":userInfo.phone,
								"color":"#000000"
							}
					}
				})
			}
    }
}
</script>

<style lang="scss" scoped>
    .release-from{
       .fromItem{
           padding:0 25px 50px 25px;
           margin: 25px 0 0 0;
           .name{
                display: flex;
                align-items: center;
                font-size: 28px;
                font-weight: bold;
                margin: 0 0 10px 0;
                &::before{
                    content: '';
                    display: block;
                    height: 24px;
                    width: 6px;
                    background: #e3af2f;
                    margin: 0 10px 0 0;
                }
           }
           input{
               width: 100%;
               height: 80px;
               line-height: 80px;
               padding: 20px;
               border: 0;
               background: #fff;
               border-radius: 10px;
           }
           textarea{
               border: 0;
               width: 100%;
               padding: 20px;
               background: #fff;
               height: 300px;
               border-radius: 10px;
           }
           .annexBox{
                padding: 15px 0 0 0;
           }
       } 
       .classifyBox{
           padding:0 25px;
           margin: 25px 0 0 0;
           h4{
               font-size: 34px;
           }
           .classifyList{
               padding: 25px 0 0 0;
               span{
                   float: left;
                   height: 64px;
                   line-height: 64px;
                   text-align: center;
                   border:1px solid #cccccc;
                   border-radius: 32px;
                   padding: 0 20px;
                   margin: 0 20px 20px 0;
                   &.selected{
                       background: #e3af2f;
                       color: #fff;
                   }
               }
           }
           .xzzj{
               margin: 10px -20px 0 -20px;
               .choise{
                   margin: 20px 0 0 20px;
                   width: 150px;
                   height: 150px;
                   border: 1px dashed #dbdada;
                   display: flex;
                   justify-content: center; 
                   align-items: center;
               }
           }
       }
    }
    .releaseBtn{
        padding: 20px 30px;
        background: #f2f2f2;
    }
</style>
